/*
 * list.c
 *
 *  Created on: 5 Nov 2009
 *      Author: Marc Pluhar <marc.pluhar@stud.hs-esslingen.de>
 */

#include "list.h"

List* list_new() {
	List* newnode;
	newnode = (List*) calloc(1, sizeof(List));
	newnode->next = NULL;
	newnode->payload = NULL;
	return newnode;
}

void list_addItem(List* cur, void* payload) {
	List * newnode;
	while (cur->next) {							/* Jump to end of list */
		cur = list_getNext(cur);
	}
	if(!cur->payload) {							/* Last node has no payload */
		cur->payload = payload;
	}
	else {
		newnode = (List*) calloc(1, sizeof(List));
		newnode->next = NULL;
		newnode->payload = payload;
		cur->next = newnode;
	}
}

void* list_getPayload(const List* src) {
	if(src)
		return src->payload;
	else
		return NULL;				/* Has to be checked from outside */
}

List* list_getNext(const List * src) {
	if(src)
		return src->next;
	else
		return NULL;				/* Has to be checked from outside */
}

list_size list_getCount(const List* src) {
	list_size ret = 0;
	List* runner;
	if (!src->payload && !src->next)	/* Both NULL? Then the list is empty */
		return ret;
	else {
		if(src->payload)				/* First item has payload */
			++ret;
		runner = list_getNext(src);
		while(runner) {
			if(runner->payload)			/* Only count not-NULL payloads */
				++ret;
			runner = list_getNext(runner);
		}
		return ret;
	}
}
